<template>
  <router-view/>
  <van-tabbar route>
    <van-tabbar-item replace to="/" icon="chat-o" :badge="chatNum > 0 ? chatNum : ''">聊天</van-tabbar-item>
    <van-tabbar-item replace to="/user" icon="friends-o">联系人</van-tabbar-item>
    <van-tabbar-item replace to="/setting" icon="setting-o" :dot="settingDot">设置</van-tabbar-item>
  </van-tabbar>
  <van-dialog v-model:show="videoFlag" 
    showCancelButton 
    :showConfirmButton="!called" 
    cancelButtonText="结束"
    confirmButtonText="接受"
    cancel-button-color="#e2155b"
    confirm-button-color="#0fc517"
    :before-close="handleBeforeClose"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <video v-show="called" ref="videoDOM" height="500px" autoplay playsinline muted></video>
    <div v-show="!called" style="display: flex; flex-wrap: wrap; justify-content: center; align-items: center;">
      <div style="padding-top: 20px;">
        <van-image
          radius="5"
          width="46"
          height="46"
          src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
        />
      </div>
      <div style="width: 100%; text-align: center; padding-bottom: 20px;">
        <span>{{ videoUid }}</span>
      </div>
    </div>
  </van-dialog>
</template>

<script setup>
import "webrtc-adapter"
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { tabStore, userListStore, videoStore, userStore } from '@/stores/mqttStore'
import { conn } from '@/util/clientUtil'
import { useRouter } from 'vue-router'
import { publish, getLoginUid } from '@/util/clientUtil'
import { format } from 'date-fns'

const router = useRouter()
const { settingDot } = storeToRefs(tabStore())
const { videoFlag, videoUid, videoOffer, videoFromCandidate, called } = storeToRefs(videoStore())
const { uid } = storeToRefs(userStore())
let pc = null
const videoDOM = ref()
let remoteStream = null

onMounted(() => {
  conn()
})

const chatNum = computed(() => {
  let num = 0;
  userListStore().userList.forEach(i => {
    num = num + i.num
  });
  return num
})

const handleCancel = () => {
  try{
    if(remoteStream){
      remoteStream.getTracks().forEach(track => track.stop())
    }
  }finally{
    handleChatVideo(null, 'invite-refuse')
  }
}

const handleConfirm = () => {
  called.value = true
  handleChatVideo(null, 'invite-ok')
}

const handleBeforeClose = () => {
  return false
}

const formatDate = (date) => {
  return format(date, "yyyy-MM-dd HH:mm:ss")
}

const getPeer = () => {
  if(!pc){
    pc = new RTCPeerConnection({
      iceServers: [
        { 
          urls: 'stun:120.78.64.113'
        },
        {
          urls: "turn:120.78.64.113:3478",
          username: "kurento",
          credential: "kurento",
        },
      ],
    })
  }
  return pc
}

const setRemoteOffer = () => {
  const remotePc = getPeer()
  remotePc.onicecandidate = event => {
    if (event.candidate) {
      handleChatVideo(event.candidate, 'invite-to-candidate')
    }
  }

  remotePc.ontrack = event => {
    console.log('ontrack', event)
    remoteStream = event.streams[0]
    videoDOM.value.srcObject = event.streams[0]
    videoDOM.value.play()
  };

  remotePc.setRemoteDescription(videoOffer.value)
    .then(() => remotePc.createAnswer())
    .then(answer => {
      remotePc.setLocalDescription(answer)
      handleChatVideo(answer, 'invite-answer')
    }).catch(error => {
      console.error('setRemoteOffer error:', error)
    });
}

const handleChatVideo = (data, key) => {
  const param = {
    fromUid: uid.value,
    toUid: videoUid.value,
    data: data,
    key: key,
    type: 'chat-video',
    date: formatDate(new Date())
  }
  publish(videoUid.value, JSON.stringify(param))
}

const handleCandidate = () => {
  pc.addIceCandidate(new RTCIceCandidate(videoFromCandidate.value))
  .catch(error => {
    console.log('from handleCandidate error:', error)
  })
  console.log('from candidate', videoFromCandidate.value)
}

watch(videoOffer, (newValue) => {
  setRemoteOffer()
})

watch(videoFromCandidate, (newValue) => {
  handleCandidate()
})
</script>
